package com.boot.utils;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class BatchProcesser<T> {

    private Consumer<Collection<T>> consumer;

    private LinkedBlockingQueue<T> dataList;

    public BatchProcesser(Integer batchSize, Consumer<Collection<T>> consumer) {
        this.consumer = consumer;
        dataList = new LinkedBlockingQueue<>(batchSize);
    }

    public void add(T data){
        if(!dataList.offer(data)){
            List<T> collect = dataList.stream().collect(Collectors.toList());
            collect.add(data);
            consumer.accept(collect);
            System.out.println("-----------");
            dataList.clear();
        }
    }

    public static void main(String[] args) {
        BatchProcesser<Integer> processer = new BatchProcesser<Integer>(10,con->{
            for (Integer integer : con) {
                System.out.println(integer);
            }
        });

        for (int i = 0; i < 100; i++) {
            processer.add(i);
        }
        System.out.println("");
    }
}
